const crypto = require('crypto');

module.exports = {
    /**
     * 响应数据
     * @param {number} code 响应码
     * @param {object} data 响应数据
     * @param {string} message 响应信息
     */
    send(code = 200, data = null, message = '请求成功') {
        this.ctx.body = {
            code,
            message,
        };
        data && (this.ctx.body.data = data);
    },
    /**
     * 生成指定的随机数
     * @param {number} len 随机字符长度
     * @param {string} allowString 字符序列
     */
    randomString(
        len = 6,
        allowCharSequence = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    ) {
        const arr = [];
        while (len > 0) {
            arr.push(
                allowCharSequence[
                    Math.floor(Math.random() * allowCharSequence.length)
                ]
            );
            len--;
        }
        return arr.join('');
    },
    /**
     * 生成uuid
     * @param {number} count 生成几组
     */
    uuid(count = 4) {
        const arr = [];
        for (let i = 0; i < count; i++) {
            arr.push(this.randomString(4));
        }
        return arr.join('-');
    },
    /**
     * 签名生成密文
     * @param {string} payload 加密字符串
     */
    encrypt(payload) {
        return crypto
            .createHmac('sha256', this.app.config.keys)
            .update(payload)
            .digest('hex');
    },
};
